import json
import os

import chardet
import requests


def random_ua():
    headers = {
        "accept-encoding": "gzip",
        "user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Mobile Safari/537.36 Edg/96.0.1054.53"
    }
    return headers


def path_creat():
    path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/static/image/'
    if not os.path.exists(path):
        os.mkdir(path)
    return path


def get_text(url):
    res = requests.get(url=url, headers=random_ua())
    res.encoidng = chardet.detect(res.content)['encoding']
    res = res.text
    data = json.loads(res)
    return data


def get_aid(bv):
    url_1 = 'https://api.bilibili.com/x/player/pagelist?bvid={}'.format(bv)

    response = get_text(url_1)
    cid = response['data'][0]['cid']

    url_2 = 'https://api.bilibili.com/x/web-interface/view?cid={}&bvid={}'.format(cid, bv)
    response_2 = get_text(url_2)

    aid = response_2['data']['aid']
    return aid


# 根据av号获取封面图片
def get_image(aid):
    url_3 = 'https://api.bilibili.com/x/web-interface/view?aid={}'.format(aid)
    response_3 = get_text(url_3)
    image_url = response_3['data']['pic']  # 获取图片的下载连接
    image = requests.get(url=image_url, headers=random_ua()).content  # 获取图片
    return image


def download(image, file_name):
    with open(file_name, 'wb') as f:
        f.write(image)


def Downimage(bvs):
    path_creat()
    path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/static/image/'
    bvss = []
    for bv in bvs:
        bv_path = path + bv + '.jpg'
        try:
            download(get_image(get_aid(bv)), bv_path)
            bvss.append(bv)
        except:
            continue
    return bvss
